'use client';

import { useState, useEffect } from 'react';

interface SiteSettings {
  title: string;
  subtitle: string;
  description: string;
  logo?: string;
  favicon?: string;
  theme: {
    primaryColor: string;
    secondaryColor: string;
    backgroundColor: string;
  };
  carousel: {
    interval: number;
    transition: string;
    autoPlay: boolean;
    pauseOnHover: boolean;
  };
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<SiteSettings>({
    title: '机器人创新实验室',
    subtitle: 'Robotics Innovation Lab',
    description: '致力于机器人技术研发与创新，培养优秀的机器人工程师',
    theme: {
      primaryColor: '#3b82f6',
      secondaryColor: '#64748b',
      backgroundColor: '#ffffff'
    },
    carousel: {
      interval: 4000,
      transition: 'smooth',
      autoPlay: true,
      pauseOnHover: true
    }
  });

  const [activeTab, setActiveTab] = useState<'basic' | 'theme' | 'carousel'>('basic');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      const response = await fetch('/api/config');
      
      if (response.ok) {
        const data = await response.json();
        
        if (data.success && data.data) {
          setSettings({
            title: data.data.title || '机器人创新实验室',
            subtitle: data.data.subtitle || 'Robotics Innovation Lab',
            description: data.data.description || '致力于机器人技术研发与创新，培养优秀的机器人工程师',
            logo: data.data.logo,
            favicon: data.data.favicon,
            theme: data.data.theme || {
              primaryColor: '#3b82f6',
              secondaryColor: '#64748b',
              backgroundColor: '#ffffff'
            },
            carousel: data.data.carousel || {
              interval: 4000,
              transition: 'smooth',
              autoPlay: true,
              pauseOnHover: true
            }
          });
        }
      } else {
        setError('Failed to fetch settings');
      }
    } catch (error) {
      setError('Network error occurred');
      console.error('Error fetching settings:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSave = async () => {
    setIsSaving(true);
    setError(null);
    
    try {
      const response = await fetch('/api/config', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(settings)
      });
      
      const data = await response.json();
      
      if (data.success) {
        alert('设置保存成功！');
      } else {
        throw new Error(data.error || 'Save failed');
      }
    } catch (error) {
      console.error('Error saving settings:', error);
      alert('保存失败，请重试');
      setError(error instanceof Error ? error.message : 'Save failed');
    } finally {
      setIsSaving(false);
    }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>, field: 'logo' | 'favicon') => {
    const file = e.target.files?.[0];
    if (file) {
      const fileName = `/api/uploads/${Date.now()}-${file.name}`;
      setSettings({ ...settings, [field]: fileName });
    }
  };

  const tabs = [
    { id: 'basic', label: '基本设置', icon: '⚙️' },
    { id: 'theme', label: '主题外观', icon: '🎨' },
    { id: 'carousel', label: '轮播设置', icon: '🔄' }
  ];

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        <span className="ml-3 text-gray-600">加载设置中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="text-red-600 mb-2">❌ 加载失败</div>
          <p className="text-gray-600">{error}</p>
          <button 
            onClick={fetchSettings}
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">网站设置</h1>
          <p className="text-gray-600 mt-1">配置网站的基本信息、主题和其他设置</p>
        </div>
        <button
          onClick={handleSave}
          disabled={isSaving}
          className={`px-4 py-2 rounded-lg text-white font-medium ${
            isSaving
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-blue-600 hover:bg-blue-700'
          } transition-colors`}
        >
          {isSaving ? '💾 保存中...' : '💾 保存设置'}
        </button>
      </div>

      <div className="bg-white rounded-lg shadow-sm border">
        {/* Tabs */}
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`py-4 px-1 border-b-2 font-medium text-sm ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                {tab.icon} {tab.label}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab Content */}
        <div className="p-6">
          {activeTab === 'basic' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-gray-900">基本设置</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    网站标题 *
                  </label>
                  <input
                    type="text"
                    value={settings.title}
                    onChange={(e) => setSettings({ ...settings, title: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    网站副标题
                  </label>
                  <input
                    type="text"
                    value={settings.subtitle}
                    onChange={(e) => setSettings({ ...settings, subtitle: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  网站描述 *
                </label>
                <textarea
                  value={settings.description}
                  onChange={(e) => setSettings({ ...settings, description: e.target.value })}
                  rows={3}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    网站Logo
                  </label>
                  <input
                    type="file"
                    onChange={(e) => handleFileUpload(e, 'logo')}
                    accept="image/*"
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                  {settings.logo && (
                    <p className="mt-2 text-sm text-gray-600">当前Logo: {settings.logo}</p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    网站图标 (Favicon)
                  </label>
                  <input
                    type="file"
                    onChange={(e) => handleFileUpload(e, 'favicon')}
                    accept="image/*"
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                  {settings.favicon && (
                    <p className="mt-2 text-sm text-gray-600">当前图标: {settings.favicon}</p>
                  )}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'theme' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-gray-900">主题外观</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    主要颜色
                  </label>
                  <div className="flex items-center space-x-3">
                    <input
                      type="color"
                      value={settings.theme.primaryColor}
                      onChange={(e) => setSettings({
                        ...settings,
                        theme: { ...settings.theme, primaryColor: e.target.value }
                      })}
                      className="w-12 h-10 border border-gray-300 rounded-lg cursor-pointer"
                    />
                    <input
                      type="text"
                      value={settings.theme.primaryColor}
                      onChange={(e) => setSettings({
                        ...settings,
                        theme: { ...settings.theme, primaryColor: e.target.value }
                      })}
                      className="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    次要颜色
                  </label>
                  <div className="flex items-center space-x-3">
                    <input
                      type="color"
                      value={settings.theme.secondaryColor}
                      onChange={(e) => setSettings({
                        ...settings,
                        theme: { ...settings.theme, secondaryColor: e.target.value }
                      })}
                      className="w-12 h-10 border border-gray-300 rounded-lg cursor-pointer"
                    />
                    <input
                      type="text"
                      value={settings.theme.secondaryColor}
                      onChange={(e) => setSettings({
                        ...settings,
                        theme: { ...settings.theme, secondaryColor: e.target.value }
                      })}
                      className="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    背景颜色
                  </label>
                  <div className="flex items-center space-x-3">
                    <input
                      type="color"
                      value={settings.theme.backgroundColor}
                      onChange={(e) => setSettings({
                        ...settings,
                        theme: { ...settings.theme, backgroundColor: e.target.value }
                      })}
                      className="w-12 h-10 border border-gray-300 rounded-lg cursor-pointer"
                    />
                    <input
                      type="text"
                      value={settings.theme.backgroundColor}
                      onChange={(e) => setSettings({
                        ...settings,
                        theme: { ...settings.theme, backgroundColor: e.target.value }
                      })}
                      className="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                  </div>
                </div>
              </div>

              {/* Preview */}
              <div className="mt-6">
                <h4 className="text-md font-semibold text-gray-900 mb-3">颜色预览</h4>
                <div className="flex space-x-4">
                  <div 
                    className="w-20 h-20 rounded-lg border flex items-center justify-center text-white font-medium"
                    style={{ backgroundColor: settings.theme.primaryColor }}
                  >
                    主色
                  </div>
                  <div 
                    className="w-20 h-20 rounded-lg border flex items-center justify-center text-white font-medium"
                    style={{ backgroundColor: settings.theme.secondaryColor }}
                  >
                    次色
                  </div>
                  <div 
                    className="w-20 h-20 rounded-lg border flex items-center justify-center text-gray-700 font-medium"
                    style={{ backgroundColor: settings.theme.backgroundColor }}
                  >
                    背景
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'carousel' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-gray-900">轮播设置</h3>
              <p className="text-gray-600">配置首页图片轮播的行为和外观</p>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    轮播间隔时间 (毫秒)
                  </label>
                  <input
                    type="number"
                    min="1000"
                    max="10000"
                    step="500"
                    value={settings.carousel.interval}
                    onChange={(e) => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, interval: parseInt(e.target.value) || 4000 }
                    })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                  <p className="mt-1 text-sm text-gray-500">
                    当前设置：每 {(settings.carousel.interval / 1000).toFixed(1)} 秒切换一次
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    过渡效果
                  </label>
                  <select
                    value={settings.carousel.transition}
                    onChange={(e) => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, transition: e.target.value }
                    })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="smooth">平滑滚动</option>
                    <option value="fade">淡入淡出</option>
                    <option value="slide">滑动切换</option>
                  </select>
                </div>
              </div>

              <div className="space-y-4">
                <div className="flex items-center">
                  <input
                    id="autoPlay"
                    type="checkbox"
                    checked={settings.carousel.autoPlay}
                    onChange={(e) => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, autoPlay: e.target.checked }
                    })}
                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <label htmlFor="autoPlay" className="ml-2 block text-sm text-gray-900">
                    启用自动轮播
                  </label>
                </div>

                <div className="flex items-center">
                  <input
                    id="pauseOnHover"
                    type="checkbox"
                    checked={settings.carousel.pauseOnHover}
                    onChange={(e) => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, pauseOnHover: e.target.checked }
                    })}
                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <label htmlFor="pauseOnHover" className="ml-2 block text-sm text-gray-900">
                    鼠标悬停时暂停轮播
                  </label>
                </div>
              </div>

              {/* 预设速度 */}
              <div>
                <h4 className="text-md font-semibold text-gray-900 mb-3">快速设置</h4>
                <div className="flex space-x-3">
                  <button
                    onClick={() => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, interval: 2000 }
                    })}
                    className="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                  >
                    快速 (2秒)
                  </button>
                  <button
                    onClick={() => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, interval: 4000 }
                    })}
                    className="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                  >
                    标准 (4秒)
                  </button>
                  <button
                    onClick={() => setSettings({
                      ...settings,
                      carousel: { ...settings.carousel, interval: 6000 }
                    })}
                    className="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                  >
                    慢速 (6秒)
                  </button>
                </div>
              </div>

              {/* 预览说明 */}
              <div className="bg-blue-50 p-4 rounded-lg">
                <h4 className="text-md font-semibold text-blue-900 mb-2">💡 设置说明</h4>
                <ul className="text-sm text-blue-800 space-y-1">
                  <li>• 轮播间隔时间：控制图片自动切换的频率</li>
                  <li>• 过渡效果：改变图片切换时的动画效果</li>
                  <li>• 自动轮播：是否启用自动图片切换功能</li>
                  <li>• 悬停暂停：鼠标移到图片上时是否暂停轮播</li>
                </ul>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}